<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class UserController extends Controller {

    public $layout = 'main';

    public function init() {
	if (user()->isGuest) {
	    $this->redirect(SITE_NAME_URL);
	}
    }

//    public function filters() {
//	return array(
//	    'accessControl'    // required to enable accessRules
//	);
//    }
//
//    public function accessRules() {
//	return array(
//	    array('allow', // allow all users to perform 'index' and 'view' actions
//		'actions' => array(),
//		'users' => array('*'),
//	    ),
//	    array('allow',
//		'actions' => array('dashboard', 'update', 'update_ideal_profile', 'view', 'view_matches', 'today_birthday', 'search', 'interested', 'dating_tips'),
//		'users' => array('@')
//	    ),
//	    array('deny', // deny everybody else
//		'users' => array('*')
//	    )
//	);
//    }

    public function actionDashboard() {
	//get some users match
	$criteria = new CDbCriteria();

	/**
	 * if user have not update ideal profile yet, system will get all people in their area
	 */
	if (user()->getModel()->ideal_profile) {
	    foreach (user()->getModel()->ideal_profile as $key => $value) {
		if ($value != null && $value) {
		    if ($key != 'age_from' && $key != 'age_to' && $key != 'height_from' && $key != 'height_to')
			$criteria->addCondition('t.' . $key . '=' . $value);
		    else {
			if ($key == 'age_from') {
			    $criteria->addCondition('t.age Between ' . $value . ' and ' . user()->getModel()->ideal_profile['age_to']);
			} else {
			    if ($key == 'height_from')
				$criteria->addCondition('t.height Between ' . $value . ' and ' . user()->getModel()->ideal_profile['height_to']);
			}
		    }
		}
	    }

	    $criteria->addCondition('t.postcode = ' . user()->getModel()->postcode . ' AND t.gender != "' . user()->getModel()->gender . '"');
	    $criteria->addCondition('t.user_id != ' . user()->id . ' and t.type!="admin"');
	    $criteria->order = 'rand()';
	    $criteria->limit = 2;
	    $aMatches = User::model()->findAll($criteria);
	}

	//get some users match
	if (isset(user()->getModel()->postcode) && user()->getModel()->postcode) {
	    $aMembers = User::model()->findAll(array(
		'condition' => 't.postcode = ' . user()->getModel()->postcode . ' and t.user_id != ' . user()->id . ' AND t.gender != "' . user()->getModel()->gender . '" and t.type!="admin"',
		'order' => 'rand()',
		'limit' => 6
	    ));
	} else {
	    $aMembers = User::model()->findAll(array(
		'condition' => 't.user_id != ' . user()->id . ' AND t.gender != "' . user()->getModel()->gender . '" and t.type!="admin"',
		'order' => 'rand()',
		'limit' => 6
	    ));
	}
	if (!isset($aMatches))
	    $aMatches = $aMembers;
	$this->render('dashboard', array('aMatches' => $aMatches, 'aMembers' => $aMembers));
    }

    /**
     * There are two page to update user: profile and account
     * 
     * @param string $type page you want to edit
     */
    public function actionUpdate($type) {
//	$model = user()->getModel();
	$model = User::model()->findByPk(user()->id);
	$success = '';

	if ($type == 'account')
	    $model->scenario = 'edit_account';
	else
	    $model->scenario = 'edit_profile';

	//ajax validate
	if (isset($_POST['ajax']) && $_POST['ajax'] == 'user-form') {
	    $model->attributes = $_POST['User'];
	    CActiveForm::validate($model);
	    Yii::app()->end;
	}

	if (isset($_POST['save'])) {
	    $avatar = $model->avatar;
	    $model->attributes = $_POST['User'];


	    $model->avatar = $avatar;
	    if ($fileUpload = CUploadedFile::getInstance($model, 'avatar')) {
		if ($uploadFileName = UploadHelper::saveAvatar($fileUpload)) {
		    $model->avatar = $uploadFileName;
		    if ($avatar) {
			deleteFile(AVATAR_PATH . $avatar);
		    }
		}
	    }

	    if ($model->validate()) {

		$model->birthday = $_POST['User']['year'] . '-' . $_POST['User']['month'] . '-' . $_POST['User']['day'];
		$model->age = intval(date('Y', time())) - intval($_POST['User']['year']);
		if (isset($_POST['Question']) && $_POST['Question']) {
		    /**
		     * answers of user are saved in more_information with serial type.
		     * key of answer array is question_id and value is text user type in
		     */
		    $moreInfo = array();
		    foreach ($_POST['Question'] as $key => $value) {
			$moreInfo[$key] = $value;
		    }
		    $model->more_info = serialize($moreInfo);
		}

		if ($model->save()) {
		    $success = 1;
		    $model->more_info = unserialize($model->more_info);
		    user()->setModel($model);
		    Yii::app()->user->setFlash('success', 'You have updated successfully!');
		}
	    }
	}
	$this->render('update', array('model' => $model, 'type' => $type));
    }

    /**
     * update ideal profile for user
     */
    public function actionUpdate_ideal_profile() {
	$model = IdealProfile::model()->find('user_id=' . user()->id);
	if (!$model) {
	    $model = new IdealProfile;
	    $model->age_to = 25;
	    $model->height_to = 7;
	}

	if (isset($_POST['save'])) {
	    $model->attributes = $_POST['IdealProfile'];

	    $model->user_id = user()->id;
	    if ($model->validate()) {
		if ($model->save()) {
		    Yii::app()->user->setFlash('success', 'You have saved successfully');

		    /**
		     * assign ideal_profile for match
		     */
		    user()->getModel()->ideal_profile = $_POST['IdealProfile'];
		    user()->setModel(user()->getModel());
		}
	    }
	}
	$this->render('update_ideal_profile', array('model' => $model));
    }

    /**
     * view profile of some user
     */
    public function actionView($id) {
	$checkList = 0;
	$model = $this->_loadModel($id);
	//get user who self flirted
	$listFlirt = Flirt::getList(user()->id);
	//check whether self flirted	
	if (array_search($id, $listFlirt) !== FALSE) {
	    $checkList = 1;
	}
	//check wheter user connected social
	$modelSocial = UserOAuth::model()->find('user_id = ' . user()->id . ' and LOWER(provider) = "facebook"');

	$this->render('view', array(
	    'model' => $model,
	    'listFlirt' => $listFlirt,
	    'checkList' => $checkList,
	    'modelSocial' => $modelSocial
	));
    }

    private function _loadModel($id) {
	$model = User::model()->findByPk($id);
	if ($model) {
	    return $model;
	} else {
	    throw new CHttpException(404, 'The page is not existed');
	}
    }

    /**
     * view matches
     */
    public function actionView_matches() {
	$model = new User('search');
	$model->unsetAttributes();
	if (isset($_GET['User']))
	    $model->attributes = $_GET['User'];

	$this->render('view_matches', array('model' => $model));
    }

    /**
     * view Onlines
     */
    public function actionWho_online() {
	$model = new User('search');
	$model->unsetAttributes();
	if (isset($_GET['User']))
	    $model->attributes = $_GET['User'];

	$this->render('who_online', array('model' => $model));
    }

    /**
     * list person who has birthday today
     */
    public function actionToday_birthday() {
	$model = new User('search');
	$model->unsetAttributes();
	if (isset($_GET['User']))
	    $model->attributes = $_GET['User'];
	$this->render('today_birthday', array('model' => $model));
    }

    /**
     * search user
     */
    public function actionSearch() {
	$error = array();
	$model = new User();
	if (isset($_GET['search'])) {

	    $criteria = new CDbCriteria();
	    //search age
	    if (isset($_GET['User']['ageFrom']) && $_GET['User']['ageFrom'] && isset($_GET['User']['ageTo']) && $_GET['User']['ageTo']) {
		if ($_GET['User']['ageFrom'] < $_GET['User']['ageTo']) {

		    $criteria->addCondition('t.age BETWEEN ' . $_GET['User']['ageFrom'] . ' AND ' . $_GET['User']['ageTo']);
		} else {
//		    $error[] = "'Age to' can not be less than 'Age from'";
		}
	    }
	    //search height
	    if (isset($_GET['User']['heightFrom']) && $_GET['User']['heightFrom'] && isset($_GET['User']['heightTo']) && $_GET['User']['heightTo']) {
		if ($_GET['User']['heightFrom'] < $_GET['User']['heightTo']) {
		    $criteria->addCondition('t.height BETWEEN ' . $_GET['User']['heightFrom'] . ' AND ' . $_GET['User']['heightTo']);
		} else {
//		    $error[] = "'Height to' can not be less than 'Height from'";
		}
	    }
	    //search location
	    if (isset($_GET['User']['postcode']) && $_GET['User']['postcode']) {
		$criteria->addCondition('t.postcode = ' . $_GET['User']['postcode']);
	    }
	    //search marital
	    if (isset($_GET['User']['marital'])) {
		$criteria->addCondition('t.marital = ' . $_GET['User']['marital']);
	    }
	    //search ethnicity
	    if (isset($_GET['User']['ethnicity'])) {
		$criteria->addCondition('t.ethnicity = ' . $_GET['User']['ethnicity']);
	    }
	    //search Relationship
	    if (isset($_GET['User']['relationship'])) {
		$criteria->addCondition('t.relationship = ' . $_GET['User']['relationship']);
	    }
	    //search zodiac
	    if (isset($_GET['User']['zodiac'])) {
		$criteria->addCondition('t.zodiac = ' . $_GET['User']['zodiac']);
	    }
	    //search smoking
	    if (isset($_GET['User']['smoking'])) {
		$criteria->addCondition('t.smoking = ' . $_GET['User']['smoking']);
	    }
	    //search build
	    if (isset($_GET['User']['build'])) {
		$criteria->addCondition('t.build = ' . $_GET['User']['build']);
	    }
	    //search Children
	    if (isset($_GET['User']['children'])) {
		$criteria->addCondition('t.children = ' . $_GET['User']['children']);
	    }
	    //search religion
	    if (isset($_GET['User']['religion'])) {
		$criteria->addCondition('t.religion = ' . $_GET['User']['religion']);
	    }
	    $criteria->addCondition('t.type != "admin"');
	    $criteria->addCondition('t.user_id != ' . user()->id);
	    $criteria->order = 't.user_id DESC';

	    $iTotalRecord = $model->count($criteria);

	    $page = new CPagination($iTotalRecord);
	    $page->pageSize = User::TOTAL_RECORD;
	    $page->applyLimit($criteria);
	    $this->render('search', array(
		'model' => $model,
		'aUsers' => $model->findAll($criteria),
		'pages' => $page,
		'iTotalRecord' => $iTotalRecord,
		'error' => $error
	    ));
	} else {
	    $this->render('search');
	}
    }

    public function actionInterested() {
	$model = new User;
	$criteria = new CDbCriteria();
	$criteria->addCondition('t.postcode=' . user()->getModel()->postcode);
	if (isset(user()->getModel()->ideal_profile['age_from']) && user()->getModel()->ideal_profile['age_from'] &&
		isset(user()->getModel()->ideal_profile['age_to']) && user()->getModel()->ideal_profile['age_to']) {
	    $criteria->addCondition('t.age BETWEEN ' . user()->getModel()->ideal_profile['age_from'] . ' AND ' . user()->getModel()->ideal_profile['age_to']);
	}
	if (isset(user()->getModel()->ideal_profile['height_from']) && user()->getModel()->ideal_profile['height_from'] &&
		isset(user()->getModel()->ideal_profile['height_to']) && user()->getModel()->ideal_profile['height_to']) {
	    $criteria->addCondition('t.age BETWEEN ' . user()->getModel()->ideal_profile['height_from'] . ' AND ' . user()->getModel()->ideal_profile['height_to']);
	}

	$iTotalRecord = $model->count($criteria);

	$pages = new CPagination($iTotalRecord);
	$pages->pageSize = 1;
	$pages->applyLimit($criteria);

	$this->render('interested', array(
	    'model' => $model,
	    'aUsers' => $model->findAll($criteria),
	    'iTotalRecord' => $iTotalRecord,
	    'pages' => $pages
	));
    }

    public function actionDating_tips() {
	$aTips = Tip::getListTips();
	$this->render('dating_tips', array('aTips' => $aTips));
    }

}
